<template>
  <div class="myResourcesIndex">
    <div class="hand-left">
      <div class="treeBox">
        <a-tree :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" block-node
          :selectedKeys="[channelId]" :tree-data="treeData" @expand="onExpand" :fieldNames="fieldNames" class="atree"
          @select="select_keys">
          <template v-slot:title="record">
            <div class="column-text">
              <div v-if="!record.edit" class="oldTreeItem">
                <span> {{ record.groupName }}</span>
                <span class="addNewTreeItem" @click="rightClick({ key: 1 }, record)"> 新建子分类 </span>
              </div>
              <div v-if="record.edit" class="editItem">
                <div class="div-input" contenteditable="true" style="-webkit-user-select: auto" ref="DIV_ipt_ref"
                  @blur="renameAddTreeSure($event, record, record.groupName)" placeholder="请输入栏目名称">
                  {{ record.groupName }}
                </div>
                <span class="deleteItem">
                  <i class="iconfont" @click="deleteItem()" style="font-size: 16px;margin-left:0">&#xe8e2;
                  </i>
                </span>
              </div>


            </div>
          </template>
        </a-tree>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, reactive, onMounted, nextTick, createVNode } from "vue";

import { dataSourceType, } from "@/type";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import getters from "@/store/getters";
import { cloneDeep } from "lodash";
//树结构数据
const fieldNames = reactive<dataSourceType>({
  title: "groupName",
  key: "id",
});
// emit
const emit = defineEmits(['selectKeys']);
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
const addmemeberBaseTables = ref<any>({ selectedRowKeys: [] }); // 添加成员basetable的ref
const treeData = ref<dataSourceType[]>([]);
const expandedKeys = ref<(string | number)[]>([]);
const selectOrg = ref<(dataSourceType)[]>([]);
const autoExpandParent = ref<boolean>(true);

const channelId = ref<number>(0);
const userInfo = getters.userInfo();
const showMenus = ref<boolean>(false);
// div输入框ref；
const DIV_ipt_ref = ref();
const addParams = ref<dataSourceType>({});
const groupId = ref<string | number>(); //资源id
const selectName = ref<string>('');
const checkedKeys = ref<any[]>([]);
const allOrgKey = ref<number[]>([]);

// 右键菜单数据
const menuLeftList = [
  {
    key: "1",
    text: "新建",
    //   disabled: !this._checkPermission('/resourceSpace', 'POST')
  },
  {
    key: "2",
    text: "重命名",
    //   disabled: !this._checkPermission('/resourceSpace', 'PUT')
  },
  {
    key: "3",
    text: "删除",
    //   disabled: !this._checkPermission('/resourceSpace', 'DELETE')
  },
];

//获取栏目层级树列表
const fetchResourceGroupTreeList = async () => {
  let data = await request.fetchResourceGroupTreeList();
  let obj = {
    groupName: "无分组资源",
    id: 0,
    children: [],
    edit: false,
    isAdd: false,
    parentId: 0,
  };
  treeData.value = [obj, ...data];
};
//展开和收起全部的操作
const onExpand = (keys: string[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};
const parentKey = ref<(string | number)[]>([]);

//获取父级id集合
const getParentKey = (id: string | number, data: dataSourceType) => {
  if (id) {
    parentKey.value.push(id);
    for (let i = 0; i < data.length; i++) {
      if (id == data[i].id) {
        getParentKey(data[i]?.parentId, data);
      }
    }
  }
};

//选择分组下的资源库
const select_keys = (item: any) => {
  if (item.length) {
    channelId.value = item[0];
    emit('selectKeys', item[0]);
  }
};

//分组重命名和新增
const renameAddTreeSure = async (e: any, data: dataSourceType, oldName: any) => {
  addParams.value = data.data;
  if (!e.target.value && !e.target.innerText) {
    loop(treeData.value, { id: data.parentId }, 1, true);
    return
  }
  if (data.isAdd) {
    if (e.target.value || e.target.innerText) {
      fetchResourceGroupAdd(e.target.value || e.target.innerText, data);
    }

  } else {
    if (e.target.value || e.target.innerText) {
      if (oldName === e.target.innerText) {
        fetchResourceGroupTreeList();
        return;
      }
      renameTreeSure(e.target.value || e.target.innerText, data);
    }
  }
};


//分组新增
const fetchResourceGroupAdd = async (groupName: string, data: dataSourceType) => {
  request
    .fetchResourceGroupAdd({
      groupName,
      parentId: data.parentId,
      userId: userInfo.userId,
    })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchResourceGroupTreeList();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

//分组重命名
const renameTreeSure = async (groupName: string, data: dataSourceType) => {
  request.fetchResourceGroupRename({
    groupName,
    parentGroupId: data.parentId,
    groupId: data.id
  }).then((res: any) => {
    if (res.code == "00000 00000") {
      fetchResourceGroupTreeList();
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  }).catch((err: any) => {
    throw new Error(err);
  });
};

//获取组织的全部id
const getAllOrgKey = (data: dataSourceType) => {
  data.length && data.map((item: any) => {
    if (!allOrgKey.value.find((jitem: number) => jitem === item.id)) {
      allOrgKey.value.push(item.id)
    }
    if (item.children && item.children.length) {
      getAllOrgKey(item.children)
    }
  })
}


// 右键点击
const rightClick = (keyObj: dataSourceType, data: any) => {
  deleteItem();
  if (data.groupName === '无分组资源') {
    return
  }
  showMenus.value = true;
  selectName.value = data.groupName
  addParams.value = data.data;
  groupId.value = data.id;
  nextTick(() => {
    loop(treeData.value, addParams.value, keyObj.key);
  })
};
const loop = (data: dataSourceType[], addParams: any, type: any, isDelete: boolean = false): any => {
  console.log(data, 'data, addParams')
  if (addParams && addParams.id == 0 && !channelId.value && isDelete) {
    data.pop();
    return
  }
  if (!addParams.id && type == 1 && !isDelete) {
    let obj = {
      groupName: "",
      id: null,
      children: [],
      edit: true,
      isAdd: true,
      parentId: 0,
    };
    data.push(obj);
    return
  }
  for (let i = 0; i < data.length; i++) {
    if (data[i].id == addParams.id) {
      // 修改值
      type == 2 ? (data[i].edit = true) : (data[i].edit = false);
      // type == 3 ? data.splice(i, 1) : ""; //删除值
      if (type == 1 && !isDelete) {
        let obj = {
          groupName: "",
          id: null,
          children: [],
          edit: true,
          isAdd: true,
          parentId: data[i].id,
        };
        data[i].children = data[i].children && data[i].children.length ? data[i].children : [];
        data[i].children.push(obj);
        parentKey.value = [];
        getParentKey(data[i].id, data);
      } else if (type == 1 && isDelete) {
        data[i].children.pop();
      }
    } else {
      if (data[i].children instanceof Array && data[i].children.length) {
        loop(data[i].children, addParams, type, isDelete);
      }
    }
  }

  nextTick(() => {
    // if (DIV_ipt_ref.value) {
    //   DIV_ipt_ref.value.focus();
    // }
    expandedKeys.value = JSON.parse(JSON.stringify(parentKey.value));
  })
};
const deleteItem = () => {
  if (DIV_ipt_ref.value) {
    DIV_ipt_ref.value.focus();
    DIV_ipt_ref.value.blur();
  }
}
const closeMenu = () => {
  showMenus.value = false;
};


//获取选择的组织
const getOrgSelectList = (data: any, id: number) => {
  data.length && data.map((jitem: dataSourceType) => {
    let obj: dataSourceType = {}
    if (jitem.id === id) {
      obj.id = jitem.id
      obj.name = jitem.name
      if (!selectOrg.value.find((sitem: any) => sitem.id === id)) {
        selectOrg.value.push(obj)
      }
    } else if (jitem.children) {
      getOrgSelectList(jitem.children, id)
    }
  })
}




//onmounted
onMounted(async () => {
  fetchResourceGroupTreeList();
});
</script>

<style lang="less" scoped>
.myResourcesIndex {
  width: 100%;
  height: calc(100% - 16px);
  display: flex;
  background-color: #fff;
  overflow: auto;

  .hand-left {
    width: 100%;
    height: calc(100%);
    position: relative;
    transition: width 0.3s;

    .treeBox {
      height: 100%;
    }

    .treeTitle {
      margin-top: 16px;
      margin-bottom: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 24px;
      background: #edf7ff;
      border-radius: 2px;
      padding: 0 4px;

      .openorclose {
        cursor: pointer;
        display: flex;
        align-items: center;
      }
    }

    ::v-deep(.ant-tree-title) {
      width: 100%;
    }

    .iconfont:hover {
      color: rgba(0, 0, 0, 0.6);
    }

    .iconfonts {
      color: rgba(0, 0, 0, 0.45);
    }


  }

  .oldTreeItem {
    &:hover {
      .addNewTreeItem {
        display: inline-block;
      }
    }

    .addNewTreeItem {
      display: none;
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #1F6DED;
      line-height: 14px;
      margin-left: 12px;
    }
  }

  .editItem {
    width: max-content;
    display: flex;

    .deleteItem {
      margin-left: 12px;

      .iconfont {
        color: rgba(0, 0, 0, 0.45);
        line-height: 32px;

        &:hover {
          color: rgba(0, 0, 0, 0.65);
        }

        &:active {
          color: rgba(0, 0, 0, 0.85);
        }
      }
    }
  }
}
</style>
<style lang="less">
.div-input {
  box-sizing: border-box;
  margin: 0;
  font-variant: tabular-nums;
  list-style: none;
  font-feature-settings: "tnum";
  position: relative;
  display: inline-block;
  width: 100%;
  min-width: 0;
  padding: 4px 11px;
  color: #000000d9;
  font-size: 14px;
  line-height: 1.5715;
  background-color: #fff;
  background-image: none;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  transition: all .3s;
  width: 234px;

  &:hover {
    border-color: var(--theme_button_bg_color, #4892fa);
    box-shadow: 0 0 0 2px var(--theme_input_focus_shadow_color, #c4e3ff);
    border-right-width: 1px !important;
    outline: 0;
  }
}
</style>
<style lang="less"></style>
